<route lang="jsonc">
{
  "layout": "default",
  "style": {
    "navigationBarTitleText": "个人资料"
  },
  "needLogin": true
}
</route>

<script lang="ts" setup>
import type { AreaItem } from '@/api/user';
import { onLoad, onShow } from '@dcloudio/uni-app'
import apiUser from '@/api/user'
import { useUserStore } from '@/store'
import { toast } from '@/utils/toast'
import { chooseAndUploadAvatar } from '@/utils/uploadImage'

defineOptions({
  name: 'UserProfile',
})

// 获取用户状态
const userStore = useUserStore()

// 表单数据
const form = reactive({
  nickname: userStore.userInfo.nickname || '',
  headimgurl: userStore.userInfo.headimgurl || '',
  sex: userStore.userInfo.sex ? String(userStore.userInfo.sex) : '0',
  provinceCode: userStore.userInfo.provinceCode || '',
  cityCode: userStore.userInfo.cityCode || '',
  districtCode: userStore.userInfo.districtCode || '',
  mobile: userStore.userInfo.mobile || '',
})

// 地区选择器相关
const showAreaPicker = ref(false)
const activeProvince = ref<AreaItem | null>(null)
const activeCity = ref<AreaItem | null>(null)
const activeDistrict = ref<AreaItem | null>(null)

// 性别选择器相关
const showSexPicker = ref(false)

// 性别选项
const sexOptions = [
  { text: '未知', value: '0' },
  { text: '男', value: '1' },
  { text: '女', value: '2' },
]

// 地区数据
const provinces = ref<AreaItem[]>([])
const cities = ref<AreaItem[]>([])
const districts = ref<AreaItem[]>([])

// 地区名称显示
const areaText = computed(() => {
  if (!form.provinceCode)
    return '请选择所在地区'

  const province = provinces.value.find(p => p.code === form.provinceCode)
  const city = cities.value.find(c => c.code === form.cityCode)
  const district = districts.value.find(d => d.code === form.districtCode)

  // 如果区县为undefined但有区县代码，尝试加载区县数据
  if (!district && form.districtCode && form.cityCode && districts.value.length === 0) {
    loadDistricts(form.cityCode)
  }

  let text = province?.name || form.provinceCode || ''
  if (city?.name)
    text += ` ${city.name}`
  else if (form.cityCode)
    text += ` ${form.cityCode}`

  if (district?.name)
    text += ` ${district.name}`
  else if (form.districtCode)
    text += ` ${form.districtCode}`

  return text || '请选择所在地区'
})

// 加载状态
const loading = ref(false)
const areaLoading = ref(false)

// 头像上传
async function handleUploadWithOptions() {
  try {
    const imageUrl = await chooseAndUploadAvatar('/app/auth/system/sts/policy')
    console.log('上传成功，头像地址:', imageUrl)
    form.headimgurl = imageUrl
  }
  catch (error) {
    // 处理错误
  }
}

// 选择头像
function chooseAvatar() {
  handleUploadWithOptions()
}

// 选择性别
function handleSexChange(e: any) {
  form.sex = e.detail.value
  showSexPicker.value = false
}

// 加载省份数据
async function loadProvinces() {
  try {
    areaLoading.value = true
    const res = await apiUser.getAreaChildList({ parentCode: '0' })
    if (res.result) {
      provinces.value = res.result as AreaItem[]

      // 如果已有选择的省份，设置为激活状态
      if (form.provinceCode) {
        activeProvince.value = provinces.value.find(p => p.code === form.provinceCode) || null
      }
    }
  }
  catch (error) {
    console.error('获取省份数据失败', error)
    toast.error('获取地区数据失败')
  }
  finally {
    areaLoading.value = false
  }
}

// 加载城市数据
async function loadCities(provinceCode: string) {
  if (!provinceCode)
    return

  try {
    areaLoading.value = true
    const res = await apiUser.getAreaChildList({ parentCode: provinceCode })
    if (res.result) {
      cities.value = res.result as AreaItem[]

      // 如果已有选择的城市，设置为激活状态
      if (form.cityCode) {
        activeCity.value = cities.value.find(c => c.code === form.cityCode) || null
      }
      else {
        activeCity.value = null
        form.cityCode = ''
      }

      // 清空区数据
      districts.value = []
      activeDistrict.value = null
      form.districtCode = ''
    }
  }
  catch (error) {
    console.error('获取城市数据失败', error)
    toast.error('获取城市数据失败')
  }
  finally {
    areaLoading.value = false
  }
}

// 加载区数据
async function loadDistricts(cityCode: string) {
  if (!cityCode)
    return

  try {
    areaLoading.value = true
    const res = await apiUser.getAreaChildList({ parentCode: cityCode })
    if (res.result) {
      districts.value = res.result as AreaItem[]

      // 如果已有选择的区，设置为激活状态
      if (form.districtCode) {
        activeDistrict.value = districts.value.find(d => d.code === form.districtCode) || null
      }
      else {
        activeDistrict.value = null
        form.districtCode = ''
      }
    }
  }
  catch (error) {
    console.error('获取区域数据失败', error)
    toast.error('获取区域数据失败')
  }
  finally {
    areaLoading.value = false
  }
}

// 打开地区选择器
async function openAreaPicker() {
  // 如果数据尚未加载，先加载数据
  if (form.provinceCode && form.cityCode && districts.value.length === 0) {
    loadInitialAreaData()
  }
  else {
    // 先加载省份数据
    if (provinces.value.length === 0) {
      await loadProvinces()
    }
    // 如果已有省份选择，加载对应城市
    if (form.provinceCode && cities.value.length === 0) {
      await loadCities(form.provinceCode)
    }

    // 如果已有城市选择，加载对应区域
    if (form.cityCode && districts.value.length === 0) {
      await loadDistricts(form.cityCode)
    }
  }

  showAreaPicker.value = true
}

// 选择省份
async function selectProvince(province: AreaItem) {
  if (activeProvince.value?.code !== province.code) {
    activeProvince.value = province
    form.provinceCode = province.code

    // 加载该省份的城市
    await loadCities(province.code)
  }
}

// 选择城市
async function selectCity(city: AreaItem) {
  if (activeCity.value?.code !== city.code) {
    activeCity.value = city
    form.cityCode = city.code

    // 加载该城市的区域
    await loadDistricts(city.code)
  }
}

// 选择区域
function selectDistrict(district: AreaItem) {
  activeDistrict.value = district
  form.districtCode = district.code
}

// 确认地区选择
function confirmAreaSelection() {
  showAreaPicker.value = false
}

// 保存用户信息
async function saveProfile() {
  if (!form.nickname) {
    toast.warning('请输入昵称')
    return
  }

  try {
    loading.value = true

    const params = {
      nickname: form.nickname,
      headimgurl: form.headimgurl,
      sex: form.sex,
      provinceCode: form.provinceCode,
      cityCode: form.cityCode,
      districtCode: form.districtCode,
    }

    const res = await apiUser.updateUserInfo(params)

    // 根据实际API响应结构判断成功
    if (res && res.status === 1) {
      toast.success('保存成功')
      // 更新用户信息
      await userStore.getUserInfo()
      setTimeout(() => {
        uni.navigateBack()
      }, 1500)
    }
    else {
      toast.error(res.msg || '保存失败')
    }
  }
  catch (error) {
    console.error('保存失败', error)
    toast.error('保存失败，请稍后重试')
  }
  finally {
    loading.value = false
  }
}

// 处理绑定手机号
function handleBindMobile() {
  uni.navigateTo({
    url: '/pages/user/newMobile?type=bindMobile',
  })
}

// 处理换绑手机号
function handleChangeMobile() {
  uni.navigateTo({
    url: '/pages/user/bindMobile',
  })
}

// 页面加载时获取用户信息
onLoad(() => {
  // 如果有省份和城市数据，立即加载所有地区数据
  if (form.provinceCode && form.cityCode) {
    loadInitialAreaData()
  }
})

// 页面显示时加载省份数据
onShow(() => {
  if (provinces.value.length === 0) {
    loadProvinces()
  }
  // 如果已有省份选择，加载对应城市
  if (form.provinceCode && cities.value.length === 0) {
    loadCities(form.provinceCode)
  }
  // 如果已有城市选择，加载对应区域
  if (form.cityCode && districts.value.length === 0) {
    loadDistricts(form.cityCode)
  }
})

// 初始化加载所有地区数据
async function loadInitialAreaData() {
  try {
    // 先加载省份数据
    const provRes = await apiUser.getAreaChildList({ parentCode: '0' })
    if (provRes.result) {
      provinces.value = provRes.result as AreaItem[]
      activeProvince.value = provinces.value.find(p => p.code === form.provinceCode) || null

      // 再加载城市数据
      if (form.provinceCode) {
        const cityRes = await apiUser.getAreaChildList({ parentCode: form.provinceCode })
        if (cityRes.result) {
          cities.value = cityRes.result as AreaItem[]
          activeCity.value = cities.value.find(c => c.code === form.cityCode) || null
          // 最后加载区数据
          if (form.cityCode) {
            const distRes = await apiUser.getAreaChildList({ parentCode: form.cityCode })
            if (distRes.result) {
              districts.value = distRes.result as AreaItem[]

              // 设置当前选中的区
              activeDistrict.value = districts.value.find(d => d.code === form.districtCode) || null

              // 如果没有找到匹配的区，尝试使用第一个区
              if (!activeDistrict.value && districts.value.length > 0) {
                activeDistrict.value = districts.value[0]
                form.districtCode = activeDistrict.value.code
              }
            }
          }
        }
      }
    }
  }
  catch (error) {
    console.error('加载地区数据失败:', error)
  }
}
</script>

<template>
  <view class="profile-container min-h-screen bg-#f7f7f7">
    <!-- 头像选择 -->
    <view class="mx-4 mb-4 rounded-lg bg-white p-4">
      <view class="flex items-center justify-between">
        <text class="text-base font-medium">头像</text>
        <view class="flex items-center" @tap="chooseAvatar">
          <image
            class="h-60px w-60px rounded-full object-cover"
            :src="form.headimgurl || 'https://cj-hz-default.oss-cn-hangzhou.aliyuncs.com/weixin/avatar.png'"
            mode="aspectFill"
          />
          <text class="iconfont icon-right ml-2 text-gray-400"></text>
        </view>
      </view>
    </view>

    <!-- 基本信息表单 -->
    <view class="mx-4 mb-4 rounded-lg bg-white">
      <!-- 昵称 -->
      <view class="flex items-center justify-between border-b border-gray-100 p-4">
        <text class="text-base">昵称</text>
        <input
          v-model="form.nickname"
          class="text-right text-base"
          placeholder="请输入昵称"
          placeholder-class="text-gray-400"
        />
      </view>

      <!-- 手机号 -->
      <view class="flex items-center justify-between border-b border-gray-100 p-4">
        <text class="text-base">手机号</text>
        <view class="flex items-center">
          <text v-if="form.mobile" class="mr-2 text-base">{{ form.mobile }}</text>
          <text v-else class="mr-2 text-base text-gray-400">未绑定</text>
          <button
            v-if="form.mobile"
            class="ml-2 border border-#0052d9 rounded-full px-3 py-1 text-xs text-#0052d9"
            @tap="handleChangeMobile"
          >
            换绑
          </button>
          <button
            v-else
            class="ml-2 rounded-full bg-#0052d9 px-3 py-1 text-xs text-white"
            @tap="handleBindMobile"
          >
            绑定
          </button>
        </view>
      </view>

      <!-- 性别选择 -->
      <view class="flex items-center justify-between border-b border-gray-100 p-4" @tap="showSexPicker = true">
        <text class="text-base">性别</text>
        <view class="flex items-center">
          <text class="mr-2 text-base">{{ sexOptions.find(item => item.value === form.sex)?.text || '未知' }}</text>
          <text class="iconfont icon-right text-gray-400"></text>
        </view>
      </view>

      <!-- 地区选择 -->
      <view class="flex items-center justify-between p-4" @tap="openAreaPicker">
        <text class="text-base">所在地区</text>
        <view class="flex items-center">
          <text class="mr-2 text-base" :class="{ 'text-gray-400': !form.provinceCode }">{{ areaText }}</text>
          <text class="iconfont icon-right text-gray-400"></text>
        </view>
      </view>
    </view>

    <!-- 保存按钮 -->
    <view class="mt-8 px-4">
      <button
        class="h-45px rounded-full bg-#0052d9 text-base text-white leading-45px"
        :disabled="loading"
        :loading="loading"
        @tap="saveProfile"
      >
        保存修改
      </button>
    </view>

    <!-- 性别选择弹窗 -->
    <wd-popup v-model="showSexPicker" position="bottom">
      <view class="bg-white">
        <view class="flex items-center justify-between border-b border-gray-100 p-4">
          <text class="text-base font-medium">选择性别</text>
          <text class="text-#0052d9" @tap="showSexPicker = false">取消</text>
        </view>
        <radio-group class="w-full" @change="handleSexChange">
          <label
            v-for="item in sexOptions"
            :key="item.value"
            class="flex items-center justify-between border-b border-gray-100 p-4"
          >
            <text class="text-base">{{ item.text }}</text>
            <radio :value="item.value" :checked="form.sex === item.value" color="#0052d9" />
          </label>
        </radio-group>
      </view>
    </wd-popup>

    <!-- 地区选择弹窗 -->
    <wd-popup v-model="showAreaPicker" position="bottom" :close-on-click-modal="false">
      <view class="bg-white">
        <view class="flex items-center justify-between border-b border-gray-100 p-4">
          <text class="text-base font-medium">选择地区</text>
          <text class="text-#0052d9" @tap="confirmAreaSelection">确定</text>
        </view>

        <view v-if="areaLoading" class="p-4">
          <view class="flex justify-center">
            <wd-loading color="#0052d9" />
          </view>
        </view>

        <view v-else class="area-selector">
          <!-- 三列布局 -->
          <view class="area-columns">
            <!-- 省份列 -->
            <scroll-view scroll-y class="area-column">
              <view
                v-for="province in provinces"
                :key="province.code"
                class="area-item"
                :class="{ 'area-item-active': activeProvince?.code === province.code }"
                @tap="selectProvince(province)"
              >
                {{ province.name }}
              </view>
            </scroll-view>

            <!-- 城市列 -->
            <scroll-view v-if="activeProvince" scroll-y class="area-column">
              <view
                v-for="city in cities"
                :key="city.code"
                class="area-item"
                :class="{ 'area-item-active': activeCity?.code === city.code }"
                @tap="selectCity(city)"
              >
                {{ city.name }}
              </view>
              <view v-if="cities.length === 0" class="area-item area-item-empty">
                暂无数据
              </view>
            </scroll-view>
            <view v-else class="area-column area-column-empty">
              <view class="area-item area-item-empty">请选择省份</view>
            </view>

            <!-- 区县列 -->
            <scroll-view v-if="activeCity" scroll-y class="area-column">
              <view
                v-for="district in districts"
                :key="district.code"
                class="area-item"
                :class="{ 'area-item-active': activeDistrict?.code === district.code }"
                @tap="selectDistrict(district)"
              >
                {{ district.name }}
              </view>
              <view v-if="districts.length === 0" class="area-item area-item-empty">
                暂无数据
              </view>
            </scroll-view>
            <view v-else class="area-column area-column-empty">
              <view class="area-item area-item-empty">请选择城市</view>
            </view>
          </view>
        </view>
      </view>
    </wd-popup>
  </view>
</template>

<style lang="scss" scoped>
.area-selector {
  height: 60vh;
  max-height: 600rpx;
}

.area-columns {
  display: flex;
  height: 100%;
}

.area-column {
  flex: 1;
  height: 100%;
  border-right: 1px solid #f0f0f0;
}

.area-column:last-child {
  border-right: none;
}

.area-column-empty {
  display: flex;
  align-items: center;
  justify-content: center;
}

.area-item {
  padding: 24rpx 20rpx;
  font-size: 28rpx;
  color: #333;
  border-bottom: 1px solid #f5f5f5;
}

.area-item-active {
  color: #0052d9;
  background-color: #f0f7ff;
  font-weight: 500;
}

.area-item-empty {
  color: #999;
  text-align: center;
}
</style>
